package com.wctj.api.base.aspect;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wctj.api.base.enums.ApiCode;
import com.wctj.api.base.exception.CustomException;
import com.wctj.api.base.utils.SignMd5Utils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Map;

@Aspect
@Slf4j
@Component
public class CheckSignAspect {

    private static final String key = "UVIUODIBDU708";  //MD5密钥
    // 定义切点Pointcut
    @Pointcut("@annotation(com.wctj.api.base.annotation.CheckSign)")
    public void excudeService() {
    }


    @Before("excudeService()")
    public void doBefore(JoinPoint joinPoint) throws JsonProcessingException {
        //log.info("开始验证签名");
        // 开始打印请求日志
        Object arg = joinPoint.getArgs()[0];
        //接口请求参数
        //将入参参数按照key,value保存的map中
        String requestData =  JSONUtil.toJsonStr(arg);
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> stringObjectMap = mapper.readValue(requestData, Map.class);

        String sign = stringObjectMap.get("sign").toString();
        SignMd5Utils signMd5Utils = new SignMd5Utils();
        if (!signMd5Utils.verify(BeanUtil.beanToMap(stringObjectMap),sign,key, "UTF-8")){
            // 打印调用 controller 的全路径以及执行方法
            log.error("验签失败 Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
            log.error("验签失败 Request parameters  : {}", requestData);
            throw new CustomException(ApiCode.AUTH_NOT_MATCH);

        }

    }

}
